package com.guit.hrms.controller;

import com.guit.hrms.dto.interview.ApplyOfferDTO;
import com.guit.hrms.dto.interview.AssignedInterviewDTO;
import com.guit.hrms.dto.interview.ResumeResponseDTO;
import com.guit.hrms.dto.interview.UpdateInterviewStatusDTO;
import com.guit.hrms.po.interview.Interviewee;
import com.guit.hrms.po.utilsPO.PageBean;
import com.guit.hrms.po.utilsPO.Result;
import com.guit.hrms.service.IntervieweeService;
import com.guit.hrms.utils.ExcelUtil;
import com.guit.hrms.utils.MD5Util;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;

@Slf4j
@Validated
@CrossOrigin
@RestController
@RequestMapping("/api/interview/interviewee")
public class IntervieweeController {
    @Autowired
    private IntervieweeService intervieweeService;

    /**
     * 应聘者上传简历
     * @param name 姓名
     * @param email 邮箱
     * @param phone 电话
     * @param resume 简历
     * @param planId 招聘计划id
     * @param deptId 应聘部门id
     * @param positionNumber 应聘岗位编号
     * @return 结果
     */
    @PostMapping("/resume/add")
    public Result addInterviewee(@NotBlank(message = "name不能为空") String name,
                            @NotBlank(message = "email不能为空") @Email(message = "email格式错误") String email,
                            @NotBlank(message = "phone不能为空") String phone,
//                            @NotBlank(message = "identificationNumber不能为空")
//                            @Length(max = 18, min = 18, message = "身份证号长度为18位")
//                                     String identificationNumber,
                            @RequestParam MultipartFile resume,
                            @NotNull(message = "planId不能为空") Integer planId,
                            @NotBlank(message = "deptId不能为空") String deptId,
                            @NotBlank(message = "positionNumber不能为空") String positionNumber){
        if (resume.isEmpty()) {
            return Result.error("文件不能为空");
        }
        Interviewee interviewee = new Interviewee();
        interviewee.setName(name);
        interviewee.setEmail(email);
        interviewee.setPhone(phone);
//        interviewee.setIdentificationNumber(identificationNumber);
        try {
            String identificationNumber = ExcelUtil.getIdentificationNumber(resume);
            interviewee.setIdentificationNumber(MD5Util.encrypt(identificationNumber));
//            if (!number.equals(identificationNumber)){
//                return Result.error("身份证号与文件不匹配");
//            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            interviewee.setResume(resume.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        interviewee.setPlanId(planId);
        interviewee.setDeptId(deptId);
        interviewee.setPositionNumber(positionNumber);
        Integer i = intervieweeService.uploadResume(interviewee);
        if (i==0){
            return Result.error("操作失败,重复提交或信息错误");
        } else {
            return Result.success("操作成功");
        }
    }

    /**
     * 根据应聘者id查找对应的简历
     * @param id 应聘者id 
     * @return 简历文件
     */
    @GetMapping(value = "/resume")
    public Result getResume(@NotNull(message = "应聘者id不能为空") Integer id) {
        try {
            Interviewee interviewee = intervieweeService.findResumeById(id);
            byte[] resumeBytes = interviewee.getResume();
            
            // 获取文件类型
            String contentType = determineContentType(resumeBytes);
            
            // 生成文件名
            String filename = interviewee.getName() + "的简历" + getFileExtension(contentType);
            
            // 将文件内容转换为Base64
            String base64Data = Base64.getEncoder().encodeToString(resumeBytes);
            
            // 构建响应对象
            ResumeResponseDTO response = new ResumeResponseDTO();
            response.setFileName(filename);
            response.setFileType(contentType);
            response.setBase64Data(base64Data);
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取简历失败", e);
            return Result.error("获取简历失败");
        }
    }

    /**
     * 根据文件字节数组判断文件类型
     */
    private String determineContentType(byte[] bytes) {
        // 检查文件魔数(Magic Numbers)
        if (bytes.length >= 4) {
            // PDF 魔数: %PDF (25 50 44 46)
            if (bytes[0] == 0x25 && bytes[1] == 0x50 && bytes[2] == 0x44 && bytes[3] == 0x46) {
                return MediaType.APPLICATION_PDF_VALUE;
            }
            
            // Excel 2007+ (.xlsx) 魔数: PK (50 4B)
            if (bytes[0] == 0x50 && bytes[1] == 0x4B) {
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }
            
            // Excel 97-2003 (.xls) 魔数: D0 CF 11 E0
            if (bytes[0] == 0xD0 && bytes[1] == 0xCF && bytes[2] == 0x11 && bytes[3] == 0xE0) {
                return "application/vnd.ms-excel";
            }

            // 图片类型判断
            if (bytes[0] == (byte)0xFF && bytes[1] == (byte)0xD8) {
                return MediaType.IMAGE_JPEG_VALUE;
            }
            if (bytes[0] == (byte)0x89 && bytes[1] == 0x50) {
                return MediaType.IMAGE_PNG_VALUE;
            }
        }
        
        // 默认返回通用二进制流类型
        return MediaType.APPLICATION_OCTET_STREAM_VALUE;
    }

    /**
     * 根据ContentType获取文件扩展名
     */
    private String getFileExtension(String contentType) {
        return switch (contentType) {
            case MediaType.APPLICATION_PDF_VALUE -> ".pdf";
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> ".xlsx";
            case "application/vnd.ms-excel" -> ".xls";
            case MediaType.IMAGE_JPEG_VALUE -> ".jpg";
            case MediaType.IMAGE_PNG_VALUE -> ".png";
            default -> "";
        };
    }

    /**
     * 查询应聘者信息
     * @param page 页码
     * @param pageSize 页大小
     * @param planId 招聘计划id
     * @param deptId 应聘部门id
     * @param positionNumber 应聘岗位编号
     * @return 应聘者信息
     */
    @GetMapping
    public Result getInterviewee(@RequestParam(defaultValue = "1") Integer page ,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 Integer planId, String deptId, String positionNumber){
        return Result.success(intervieweeService.getInterviewee(page, pageSize, planId, deptId, positionNumber));
    }

    /**
     * 为应聘者分配面试安排
     * @param assignedInterviewDTO 面试安排情况
     * @return Result
     */
    @PostMapping
    public Result assignedInterviewForInterviewee(@RequestBody @Validated AssignedInterviewDTO assignedInterviewDTO){
        return intervieweeService.assignedInterviewForInterviewee(assignedInterviewDTO) == 0 ? Result.error("分配失败,请确定信息正确且没有重复安排！") : Result.success();
    }

    /**
     * 取消应聘者的面试安排
     * @param assignedInterviewDTO 面试安排情况
     * @return Result
     */
    @PostMapping("/cancel")
    public Result cancelIntervieweesInterview(@RequestBody @Validated AssignedInterviewDTO assignedInterviewDTO){
        return intervieweeService.cancelIntervieweesInterview(assignedInterviewDTO) == 0 ? Result.error("取消失败,请确定信息正确！") : Result.success();
    }

    /**
     * 修改应聘者面试状态
     * @param updateInterviewStatusDTO 面试状态信息
     * @return Result
     */
    @PutMapping
    public Result updateInterviewStatus(@RequestBody UpdateInterviewStatusDTO updateInterviewStatusDTO){
        return intervieweeService.updateInterviewStatus(updateInterviewStatusDTO) == 0 ? Result.error("更新失败,请确定信息正确！") : Result.success();
    }

    /**
     * 删除应聘者信息
     * @param intervieweeIds 应聘者id
     * @return Result
     */
    @DeleteMapping("/{intervieweeIds}")
    public Result deleteInterviewee(@PathVariable List<Integer> intervieweeIds){
        return intervieweeService.deleteInterviewee(intervieweeIds) == 0 ? Result.error("删除失败,请确定信息正确！") : Result.success();
    }

    /**
     * 为应聘者申请offer
     * @param applyOfferDTO offer信息
     * @return Result
     */
    @PostMapping("/offer")
    public Result applyOfferForInterviewee(@RequestBody ApplyOfferDTO applyOfferDTO){
        return intervieweeService.applyOfferForInterviewee(applyOfferDTO) == 0 ? Result.error("操作失败,请确定信息正确！") : Result.success();
    }

    /**
     * 上传应聘者offer接受结果
     * @param offerToken offer唯一标识
     * @param result offer接受结果
     * @return Result
     */
    @PostMapping("/offer/result")
    public Result uploadOfferAcceptResult(String offerToken, Integer result){
        return intervieweeService.uploadOfferAcceptResult(offerToken,result) == 1 ? Result.success() : Result.error("操作失败,请确定信息正确！");
    }

    /**
     * 获取offer接受结果
     * @param page 页码
     * @param pageSize 每页大小
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param result offer接受结果
     * @return Result
     */
    @GetMapping("/offer/result/get")
    public Result getOfferResult(@RequestParam(defaultValue = "1")Integer page,
                                 @RequestParam(defaultValue = "10")Integer pageSize,
                                 LocalDateTime startTime, LocalDateTime endTime, Integer result){

        PageBean pageBean =  intervieweeService.getOfferResult(page,pageSize,startTime,endTime,result);

        return Result.success(pageBean);
    }

}
